package com.gps.pe.dao;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

import com.gps.pe.exception.DAOConfigurationException;

/**
 * This class is based on Singleton Design Pattern to get database connection
 * 
 * @author GPS
 *
 */
public final class DatabaseConnection {
	private static final Logger LOGGER = Logger.getLogger(DatabaseConnection.class);
	private static final DatabaseConnection databaseConnection = new DatabaseConnection();
	private DataSource dataSource = null;

	/**
	 * Method return single instance of database connection object
	 * 
	 * @return
	 */
	public static DatabaseConnection getInstance() {
		return databaseConnection;
	}

	/**
	 * Method return database connection
	 * 
	 * @return
	 * @throws SQLException
	 */
	public Connection getConnection() throws DAOConfigurationException {
		Connection connection = null;
		if (dataSource != null) {
			try {
				connection = dataSource.getConnection();
			} catch (SQLException se) {
				LOGGER.error("Problem to get db Connection from data source..." + se);
				throw new DAOConfigurationException("Problem to get database connection using Datasource", se);
			}
		} else {
			LOGGER.fatal("Data Source is null...");
		}

		return connection;
	}

	/**
	 * Method initialize DataSource using JNDI lookup
	 */
	private DatabaseConnection() {
		try {
			LOGGER.info("Instantiating Database Connection Object...");
			// Get DataSource
			Context initContext = new InitialContext();
			Context envContext = (Context) initContext.lookup("java:/comp/env");
			dataSource = (DataSource) envContext.lookup("jdbc/GpsPeDB");
			LOGGER.info("Successfully instantiated Database Connection Object...");
		} catch (NamingException e) {
			LOGGER.fatal("Problem to configure context.xml to lookup [jdbc/MySQLDB] from JNDI...", e);
		}
	}
}
